package com.keeley.ctrl;

import java.util.Date;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.keeley.exception.TiebaException;
import com.keeley.kit.TieBaKit;
import com.keeley.model.Vest;
import com.keeley.model.VestItem;
import com.keeley.model.VestWinning;

public class VestItemController  extends AdminBaseController<VestItem>{
	public VestItemController() {
		super(VestItem.class);
	}
	/*
	 * 开始投票
	 */
	public void vote(){
		try{
			
			VestItem vestItem = VestItem.dao.findById(getPara());
			Integer off = vestItem.getInt("vest_line");
			if(off==null) off = 0;
			Integer num = vestItem.getInt("vest_num");
			if(num==null) num = 500;
			
			List<Vest> vestList = Vest.dao.findVest(off,num);
			Db.update("update t_vest_item set vest_line=? where forumid=?",off+num,vestItem.get("forumid"));
			int index=0;
			int suc=0;
			for(Vest v : vestList){
				try{
					index++;
					int no=TieBaKit.poll(vestItem, v);
					if(no==0) {
						suc++;
						if (vestItem.getInt("type")==1){
							new VestWinning()
							.set("username", v.get("name"))
							.set("password", v.get("password"))
							.set("forumName", vestItem.get("forumName"))
							.set("createTime", new Date()).save();
							log.info("中奖");
						}
					}
					createCommon(no,"投票成功 no="+no,v.getStr("name"));
				}catch(TiebaException te){
					Db.update("update t_vest_item set vest_line=? where forumid=?",off+index,vestItem.get("forumid"));
					createCommon(-1,"投票异常"+te.getErrorMsg(),v.getStr("name"));
				}catch(Exception tee){
					Db.update("update t_vest_item set vest_line=? where forumid=?",off+index,vestItem.get("forumid"));
					createCommon(-1,"投票异常,投票次数 "+index+",成功次数"+suc,v.getStr("name"));
					return;
				}
			}
			//vestItem.set("vest_line", off+num).update();
			rendJson_(true, "操作完成 成功个数"+suc);
		}catch(Exception e){
			e.printStackTrace();
			rendJson_(false, "错误");
		}
	}
}
